import React, { useState, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { setCookies, PswToAesV5, getBrowserName } from '@/utils';
import { httpPost } from '@/axios';
import { Button, Form, Input, Select } from 'antd';

const HomeView = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [form] = Form.useForm()
  const [userList, setUserList] = useState([
    { text: '07-报表员', value: "07" },
  ]);

  const onFinish = async (value) => {
    const { password } = value;

    const result = await httpPost('/user/login', {...value, password: PswToAesV5(password), liulanqi: getBrowserName() });
    const res = result?.data
    if (res) {
      const data = userList.find((item) => item.value === value.userId);
      localStorage.setItem('userInfo', JSON.stringify(data));
      dispatch({ type: 'SET_USER_INFO', payload: data })
      setCookies('token', res?.token);
      navigate('/report-form');
    }
  }
  useEffect(() => {
    localStorage.clear();
  }, [])
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
      <Form labelCol={{ span: 4 }} style={{ width: 400 }} wrapperCol={{ span: 16 }} onFinish={onFinish}>
        <Form.Item label="用户名" name="userId"
          rules={[
            {
              required: true,
              message: '请选择用户',
            },
          ]}
        >
          <Select>
            {userList.map((item) => (
              <Select.Option key={item.value} value={item.value}>
                {item.text}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
          ]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>
        <Button style={{ width: 300, marginLeft: 20 }} type="primary" htmlType="submit">
          登陆
        </Button>
      </Form>
    </div>
  )
}

export default HomeView;
